package com.team.service.impl;

import com.team.dao.PermissionMapper;
import com.team.entity.Admin;
import com.team.entity.Permission;
import com.team.service.PermissionService;
import com.team.util.WebUtil;
import com.team.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * -*- coding:utf-8 -*-
 *
 * @author 太阳偷渡青山
 * @software IntelliJ IDEA
 * @date 2022/10/13 16:29
 * @Description
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Result findByAdminId() {
        Admin admin = (Admin) WebUtil.getSession().getAttribute("admin");
        List<Permission> permissionList = permissionMapper.selectByLoginAccount(admin.getId());
        List<Permission> permissions = hierarchy(permissionList);
        return new Result(200,"查询成功",permissions);
    }

    /**
     * 建立菜单
     * @param permissionList
     * @return
     */
    private List<Permission> hierarchy(List<Permission> permissionList){

        //1.一级菜单
        List<Permission> firsts=new ArrayList<>();
        for (Permission permission:permissionList){
            if(permission.getMenuParentId()==0){
                firsts.add(permission);
            }
        }

        //2.查询一级菜单下的二级菜单
        for(Permission first:firsts){
            List<Permission> children=new ArrayList<>();
            for(Permission p:permissionList){
                if(first.getId().equals(p.getMenuParentId())){
                    children.add(p);
                }
            }
            first.setChildren(children);
        }

        return firsts;
    }

    /**
     * 根据角色id查询所具有的权限
     * @param roleId
     * @return
     */
    @Override
    public Result findByRoleId(Integer roleId) {
        List<Permission> permissions = permissionMapper.selectPersimmionAll();
        List<Permission> firsts = hierarchy(permissions);
        List<String> integers = permissionMapper.selectByRoleId(roleId);
        Map<String, Object> map = new HashMap<>();
        map.put("firsts",firsts);
        map.put("integers",integers);
        return new Result(200,"查询成功",map);
    }

    @Override
    public Result qr(Integer roleId, Integer[] permissionIds) {
        //1. 删除该角色具有的权限
        permissionMapper.deleteByRoleId(roleId);
        //2. 批量添加权限
        permissionMapper.batchPermission(roleId,permissionIds);

        return new Result (200,"分配成功");
    }


    public Result distribute(Integer roleId, Integer[] permissionIds) {
        permissionMapper.deleteByRoleId(roleId);
        //2. 批量添加权限
        permissionMapper.batchPermission(roleId,permissionIds);

        return new Result (200,"分配成功");
    }

}
